package com.gcloud.googledrive;

import java.io.IOException;

import com.google.api.client.http.GenericUrl;
import com.google.api.client.http.HttpResponse;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.model.File;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

public class DownloadGoogleFile extends AsyncTask<Void, Long, Boolean> {

	private Drive service;
	private File file;
	private Context context;
	private long sizeFile;
	private final ProgressDialog dialog;
	private static String TAG = DownloadGoogleFile.class.getSimpleName();

	public DownloadGoogleFile(Drive service, File file, Context context) {
		this.service = service;
		this.file = file;
		this.context = context;
		this.sizeFile = file.getFileSize();
		dialog = new ProgressDialog(context);
		if (context != null) {
			dialog.setMax(100);
			dialog.setMessage("Downloading " + file.getTitle());
			dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			dialog.setProgress(0);
			dialog.show();
		}
	}

	@Override
	protected Boolean doInBackground(Void... params) {
		String methodName = "doInBackground()";
		Log.i(TAG, methodName);
		if (file.getDownloadUrl() != null && file.getDownloadUrl().length() > 0) {
			try {
				HttpResponse resp = service.getRequestFactory()
						.buildGetRequest(new GenericUrl(file.getDownloadUrl()))
						.execute();
				Log.i(TAG, "Everything goes well");
			} catch (IOException e) {
				Log.e(TAG, "IOException downloading: " + e);				
				return false;
			}
		} else {
			Log.i(TAG, "Is not a download file getDownloadUrl() = null");
			return false;
		}
		return true;
	}

	@Override
	protected void onProgressUpdate(Long... progress) {
		if (context != null) {
			int percent = (int) (100.0 * (double) progress[0] / sizeFile + 0.5);
			dialog.setProgress(percent);
		} else {
			super.onProgressUpdate(progress);
		}
	}

	@Override
	protected void onPostExecute(Boolean result) {
		dialog.dismiss();
		if (result) {
			showToast("Download sucess");
		} else {
			showToast("Download unsucess");
		}
	}

	private void showToast(String message) {
		if (context != null) {
			Toast toast = Toast.makeText(context, message, Toast.LENGTH_LONG);
			toast.show();
		}
	}

}
